//
//  CHKeyBoard.swift
//  CHSimpleUI
//
//  Created by cyptt on 2022/7/18.
//

import UIKit
import SnapKit
public enum CHKeyBoardStyle : Int {
    
    case number = 0    //纯数字
    case decimal = 1  //小数点
}
public class CHKeyBoard: UIView {

  
    let BTN_TAG:NSInteger = 4000
    let keyDataArr:[String] = ["1","2","3","4","5","6","7","8","9",".","0",""]
    var textFs:[UITextField]=[]
    var keybordV:CHKeyBoard?
    let window1:UIWindow = UIApplication.shared.keyWindow!
    
    let W_W:CGFloat = UIApplication.shared.keyWindow!.bounds.size.width
    let W_H:CGFloat = UIApplication.shared.keyWindow!.bounds.size.height
    
    //健康数据
    var board_H:CGFloat = 322
    
    var title_h:CGFloat = 40 //顶部tile 高度
    let corRadius:CGFloat = 2
    // 输入框
    let textF_W_H:CGFloat = 40  //输入框宽高
    let textMargin:CGFloat = 8  //输入框间距
    var textMargin_L_R:CGFloat = 0  //输入框间距
    var textMarginTop:CGFloat = 30   //输入框距离顶部距离
    
    //键盘按钮
    let btn_margin_L_R:CGFloat = 10 //距离左右距离
    let btn_margin:CGFloat = 4 //键盘按钮间距
    var btn_W:CGFloat = 0 // 按钮宽度
    var btn_marginTop:CGFloat = 100 //距离顶部距离
    let btn_H:CGFloat = 49 //按钮高度
    //右边确定按钮
    let rightBtnW:CGFloat = 64
    let rightBtnH:CGFloat = 102
    
    //tile 距离顶部
    private let title_margin_top:CGFloat = 17
    
    
    
    
    
    //字体
//    let btnFont:UIFont = UIFont.fontNames(forFamilyName: <#T##String#>)
    
    //颜色
     let keyboardBackColor:UIColor = UIColor.init(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1)
    
    let textBorderColor:UIColor = UIColor.init(red: 183/255.0, green: 183/255.0, blue: 183/255.0, alpha: 1)
    
    let btnColor:UIColor = UIColor.white
    private var sureBtnColor:UIColor = UIColor.init(red: 23/255.0, green: 203/255.0, blue: 142/255.0, alpha: 1)
    let btnTitleColor:UIColor = UIColor.init(red: 43/255.0, green: 51/255.0, blue: 58/255.0, alpha: 1)
    
    let sureTitleColor:UIColor = UIColor.white
    private var misblankDis:Bool = false
    private var sureBlockCallBack:((_ keyText:String) -> ())?
    
    private var dismisBlockCallBack:(() -> ())?
    
    private var showTitle:String? //显示的title
    private var mReturnIsRemove:Bool = true
    public override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    public init(){
        let react:CGRect = window1.bounds
        
        super.init(frame: react)
        
        textMargin_L_R = (W_W - 5*textMargin - 6*textF_W_H)/2
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0.3)
       
        window1.addSubview(self)
    }
    
    /*
     确定回调
     */
    public func sureKeyBoardClick(clouse:@escaping(_ keyText:String)-> Void){
        self.sureBlockCallBack = clouse
    }
    
    /*
     点击消失键盘
     */
    public func dismisKeyBoardClick(clouse:@escaping()-> Void){
        self.dismisBlockCallBack = clouse
    }
    

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /*
     显示键盘
     @param type 键盘类型 CHKeyBoardStyle
     @param isblankDis 点击空白是否消失键盘 true 消失，否则不消失
     @param retrunIsRemove 返回是否关闭键盘 默认关闭
     */
    public func show(type:CHKeyBoardStyle,isblankDis:Bool? = nil,title:String? = nil,returnIsRemove:Bool = true,sureColor:UIColor? = UIColor.init(red: 23/255.0, green: 203/255.0, blue: 142/255.0, alpha: 1)){
         
        self.sureBtnColor = sureColor!
        self.showTitle = title
        if isblankDis != nil{
            misblankDis = isblankDis!
        }
        self.mReturnIsRemove = returnIsRemove
        
        if self.showTitle != nil{
            self.title_h = self.title_h + 0
        }else{
            self.title_h = 0
        }
        
        self.board_H = self.board_H + self.title_h
        self.btn_marginTop = self.btn_marginTop + self.title_h
        self.textMarginTop = self.textMarginTop + self.title_h
        self.keybordV = CHKeyBoard.init(frame: CGRect.init(x: 0, y:-self.W_H, width: self.W_W, height: self.board_H))
        
        self.keybordV?.backgroundColor = self.keyboardBackColor
       
        self.addSubview(self.keybordV!)
        
        UIView.animate(withDuration: 2) {
            self.keybordV?.snp.makeConstraints({ make in
                make.left.equalTo(0)
                make.width.equalTo(self.W_W)
                make.height.equalTo(self.board_H)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(self.safeAreaLayoutGuide)
                } else {
                    make.bottom.equalTo(0)
                }
            })
        }
        
        
     
        
        let safeView:UIView = UIView()
        safeView.backgroundColor = keyboardBackColor
        self.addSubview(safeView)
        safeView.snp.makeConstraints({ make in
            make.left.equalTo(0)
            make.top.equalTo(keybordV!.snp.bottom).offset(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
        })
         
        
        if self.showTitle != nil {
            let titleL:UILabel = UILabel.init()
            titleL.textColor = UIColor.init(red: 67/255.0, green: 67/255.0, blue: 67/255.0, alpha: 1)
            titleL.font = UIFont.systemFont(ofSize: 18)
            titleL.text = self.showTitle
            titleL.textAlignment = .center
            self.keybordV?.addSubview(titleL)
            titleL.snp.makeConstraints { make in
                make.left.centerX.equalToSuperview()
                make.top.equalTo(self.title_margin_top)
            }
        }
      
         
         
         for i in 0...5{
             let text_x:CGFloat = textMargin_L_R + CGFloat(i)*(textF_W_H + textMargin)
             let textRect:CGRect = CGRect.init(x: text_x, y: textMarginTop, width: textF_W_H, height: textF_W_H)
             let textF:UITextField = UITextField.init(frame: textRect)
             
             textF.layer.borderWidth = 0.5
             textF.layer.borderColor = textBorderColor.cgColor
             textF.layer.cornerRadius = corRadius
             textF.layer.masksToBounds = true
             textF.inputView = UIView.init(frame: CGRect.zero)
             textF.textAlignment  = .center
             textF.font = UIFont.systemFont(ofSize: 27)
             textF.isUserInteractionEnabled = false
             keybordV?.addSubview(textF)
             textF.textColor = btnTitleColor
             
           
             self.textFs.append(textF)
         }
        
        btn_W = (W_W - 2*btn_margin_L_R - 3*btn_margin - rightBtnW)/3
        for i in 0...11{
       
            if type == .number{
                if i == 9{
                    continue
                }
            }
           
            let btn_x:CGFloat = btn_margin_L_R + CGFloat(i%3)*(btn_W + btn_margin)
            let btn_y:CGFloat = (CGFloat(i/3) * (btn_H + btn_margin)) + btn_marginTop
           
            let btnRect:CGRect = CGRect.init(x: btn_x, y: btn_y, width: btn_W, height: btn_H)
            let btn:UIButton = UIButton.init(type: .custom)
            btn.frame = btnRect
            btn.backgroundColor = btnColor
            btn.layer.cornerRadius = corRadius
            btn.layer.masksToBounds = true
            btn.setTitle(self.keyDataArr[i], for: UIControl.State.normal)
            btn.setTitleColor(btnTitleColor, for: UIControl.State.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 27)
            btn.tag = BTN_TAG + i
            btn.addTarget(self, action: #selector(keyBtnClick(btn:)), for: .touchUpInside)
            keybordV?.addSubview(btn)
            btn.titleLabel?.textAlignment = .center
            if i == 11{
                let disimage:UIImage? =  UIImage.init(named: "ch_keyboard_dismis", in: CHBundle.bundle(), compatibleWith: nil)
                btn.setImage(disimage, for: .normal)
            }
        }
        
        let chaBtn:UIButton = UIButton.init(type: .custom)
        chaBtn.backgroundColor = btnColor
        chaBtn.layer.cornerRadius = corRadius
        chaBtn.layer.masksToBounds = true
        
  
        let cancelImage:UIImage? =  UIImage.init(named: "ch_keyboard_cancel", in: CHBundle.bundle(), compatibleWith: nil)
        chaBtn.setImage(cancelImage, for: UIControl.State.normal)
        keybordV?.addSubview(chaBtn)
        
        chaBtn.addTarget(self, action: #selector(chaBtnClick(btn:)), for: .touchUpInside)
        chaBtn.snp.makeConstraints { make in
            make.width.equalTo(rightBtnW)
            make.height.equalTo(rightBtnH)
            make.right.equalTo(-btn_margin_L_R)
            make.top.equalTo(btn_marginTop)
        }
        
        
        
        
        let sureBtn:UIButton = UIButton.init(type: .custom)
        sureBtn.layer.cornerRadius = corRadius
        sureBtn.layer.masksToBounds = true
        sureBtn.backgroundColor = self.sureBtnColor
        keybordV?.addSubview(sureBtn)
        
        sureBtn.addTarget(self, action: #selector(sureBtnClick(btn:)), for: .touchUpInside)
        sureBtn.setTitleColor(sureTitleColor, for: UIControl.State.normal)
        sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.snp.makeConstraints { make in
            make.width.equalTo(rightBtnW)
            make.height.equalTo(rightBtnH)
            make.right.equalTo(-btn_margin_L_R)
            make.top.equalTo(chaBtn.snp.bottom).offset(btn_margin)
        }
    }
    
    /*
     是否隐藏 默认不隐藏 true 隐藏 false不应成
     */
    public func textFisSecureTextEntry(isSecure:Bool){
        for textItem in self.textFs{
            textItem.isSecureTextEntry = isSecure
        }
    }
    //点击了
    public  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  
        let touch:UITouch? = touches.first
        let point:CGPoint? = touch?.location(in: self)
  
        if self.keybordV != nil{
            if self.keybordV!.frame.contains(point!){
                print("点击了keybord内")
            }else{
                print("点击了keybord外")
                if self.misblankDis  == true{
                    //更新了
                    if self.dismisBlockCallBack != nil {
                        self.dismisBlockCallBack!()
                    }
                    if self.mReturnIsRemove == true{
                        self.removeFromSuperview()
                        
                    }
                 
                }else{
                    
                }
            }
        }else{
            print("点击了keybord内")
        }
      
  
    }
    

    
    
}

//按钮点击
extension CHKeyBoard{
    @objc func keyBtnClick(btn:UIButton){
 
        let tag:NSInteger = btn.tag - BTN_TAG
        print(tag)

        if tag == 11 {
            if self.dismisBlockCallBack != nil {
                self.dismisBlockCallBack!()
            }
            if self.mReturnIsRemove == true{
                self.removeFromSuperview()
            }
          
        }else{
            for textItem in self.textFs{
                if textItem.text == ""{
                    textItem.text = self.keyDataArr[tag]
                    if textItem.isSecureTextEntry == true{
                        
                        textItem.isSecureTextEntry = false
                        DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + 0.3) {
                            textItem.isSecureTextEntry = true
                        }
                      
                    }
                    break
                }
            }
        }
      
    
        
    }
    
    @objc func sureBtnClick(btn:UIButton){
 
     
        var isALL:Bool = true
        var allText:String = ""
        for textItem in self.textFs{
            if textItem.text == ""{
                isALL = false
                break
            }else{
                allText = allText + textItem.text!
            }
        }
        if isALL == true{
            
            if self.sureBlockCallBack != nil{
                self.sureBlockCallBack!(allText)
            }
            if self.mReturnIsRemove == true{
                self.removeFromSuperview()
            }
        }
      
    }
    
    @objc func chaBtnClick(btn:UIButton){
 
        for (index,textItem) in self.textFs.enumerated().reversed(){
            print("index----",index)
            if textItem.text != ""{
                textItem.text =  ""
                break
            }
        }
   
    }

}




